//
//  CarmeraViewController.m
//  自定义相机
//
//  Created by 谭伟 on 2017/8/7.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "CarmeraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface CarmeraViewController ()<UIGestureRecognizerDelegate>
/**
 *  AVCaptureSession对象来执行输入设备和输出设备之间的数据传递
 */
@property (nonatomic, strong) AVCaptureSession* session;
/**
 *  输入设备
 */
@property (nonatomic, strong) AVCaptureDeviceInput* videoInput;
/**
 *  照片输出流
 */
@property (nonatomic, strong) AVCaptureStillImageOutput* stillImageOutput;
/**
 *  预览图层
 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer* previewLayer;
/**
 *  记录开始的缩放比例
 */
@property(nonatomic,assign)CGFloat beginGestureScale;
/**
 *  最后的缩放比例
 */
@property(nonatomic,assign)CGFloat effectiveScale;

@property (weak, nonatomic) IBOutlet UIView *backView;

/* 是否是潜质摄像头 */
@property (assign, nonatomic) BOOL isUsingFrontFacingCamera;

@property (weak, nonatomic) IBOutlet UIButton *leftButton;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;
//拍照文字提醒
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

/* 点击了拍照 */
@property (assign, nonatomic) BOOL isClick;
/*拍照后的照片 */
@property(nonatomic,strong) NSData *jpegData;

/* 占位的imageView */
@property (weak, nonatomic) IBOutlet UIImageView *placeImageView;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeightConstraint;

@property (weak, nonatomic) IBOutlet UIButton *carmeraButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cameraCenterConstraint;



@end

@implementation CarmeraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initAVCaptureSession];
    [self setUpGesture];
    self.effectiveScale = self.beginGestureScale = 1.0f;
    self.placeImageView.image = [UIImage imageNamed:_imageStr];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    if (self.session) {
        
        [self.session startRunning];
    }
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:YES];
    
    if (self.session) {
        
        [self.session stopRunning];
    }
}


- (void)initAVCaptureSession{
    
    self.session = [[AVCaptureSession alloc] init];
    
    NSError *error;
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃
    [device lockForConfiguration:nil];
    //设置闪光灯为自动
    if ([device isFlashModeSupported:AVCaptureFlashModeAuto]) {
        [device setFlashMode:AVCaptureFlashModeAuto];
    }
    [device unlockForConfiguration];
    
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    //输出设置。AVVideoCodecJPEG   输出jpeg格式图片
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
    
    //初始化预览图层
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    NSLog(@"%f",kMainScreenWidth);
    self.previewLayer.frame = CGRectMake(0, 0,kMainScreenWidth, kMainScreenHeight - 64);
    self.backView.layer.masksToBounds = YES;
    [self.backView.layer addSublayer:self.previewLayer];
//    self.imageView.userInteractionEnabled = YES;
//    [self.imageView.layer addSublayer:self.previewLayer];
}

//导航栏，状态栏透明
- (UIImage *)navigationBarBackgroundImage {
    return [UIImage new];
}

//线条隐藏
- (UIImage *)navigationBarShadowImage {
    return [UIImage new];
}


- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
    if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
        result = AVCaptureVideoOrientationLandscapeRight;
    else if ( deviceOrientation == UIDeviceOrientationLandscapeRight )
        result = AVCaptureVideoOrientationLandscapeLeft;
    return result;
}


#pragma 创建手势
- (void)setUpGesture{
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    pinch.delegate = self;
    [self.backView addGestureRecognizer:pinch];
}

#pragma mark gestureRecognizer delegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}

#pragma mark -Action

- (IBAction)takePhotoAction:(UIButton *)sender {
   
    AVCaptureConnection *stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
    AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation];
    [stillImageConnection setVideoOrientation:avcaptureOrientation];
    [stillImageConnection setVideoScaleAndCropFactor:self.effectiveScale];
    
    kdeclare_weakself;
    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        NSData *jpegData;
        if (@available(iOS 10.0, *)) {
            jpegData = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:imageDataSampleBuffer previewPhotoSampleBuffer:imageDataSampleBuffer];
            
        } else {
            jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        }
        weakSelf.jpegData = jpegData;
//        self.placeImageView.image = [UIImage imageNamed:@""];
//        self.imageView.image = [UIImage imageWithData:jpegData];
//        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        weakSelf.placeImageView.hidden = YES;
        [weakSelf.session stopRunning];
    }];
//    _isClick = !_isClick;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([weakSelf.leftButton.titleLabel.text isEqualToString:@"取消"]) {
            weakSelf.tipLabel.hidden = YES;
            weakSelf.bottomViewHeightConstraint.constant = 88;
            weakSelf.cameraCenterConstraint.constant = 0;
            weakSelf.carmeraButton.hidden = YES;
            [weakSelf.leftButton setTitle:@"重拍" forState:UIControlStateNormal];
            [weakSelf.rightButton setTitle:@"使用照片" forState:UIControlStateNormal];
            [weakSelf.rightButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        }else {
            [weakSelf.leftButton setTitle:@"取消" forState:UIControlStateNormal];
            [weakSelf.rightButton setTitle:@"" forState:UIControlStateNormal];
            [weakSelf.rightButton setImage:[UIImage imageNamed:@"rotate_carmera"] forState:UIControlStateNormal];
        }
        

    });
    
}

//左边按钮，取消／重拍
- (IBAction)leftButtonAction:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"取消"]) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {//重拍
        [self.session startRunning];
        self.placeImageView.hidden = NO;
        _tipLabel.hidden = NO;
        _bottomViewHeightConstraint.constant = 108;
        
        _cameraCenterConstraint.constant = 20;
        _carmeraButton.hidden = NO;
        self.placeImageView.image = [UIImage imageNamed:_imageStr];
        self.imageView.image = [UIImage imageNamed:@""];
    
        [sender setTitle:@"取消" forState:UIControlStateNormal];
        [_rightButton setTitle:@"" forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"rotate_carmera"] forState:UIControlStateNormal];
    }
    
}


//右侧按钮切换镜头，使用照片
- (IBAction)rightButtonAction:(UIButton *)sender {
        if ([sender.titleLabel.text isEqualToString:@"使用照片"]) {
            UIImage *image = [UIImage imageWithData:_jpegData];
            if (_imageBlock != nil) {
                _imageBlock(image);
            }
//            [self saveImageFromCamera];
            //        [library writeImageDataToSavedPhotosAlbum:jpegData metadata:(__bridge id)attachments completionBlock:^(NSURL *assetURL, NSError *error) {
            //
            //        }];


        [self dismissViewControllerAnimated:YES completion:nil];
    }else {//切换镜头
        AVCaptureDevicePosition desiredPosition;
        if (_isUsingFrontFacingCamera){
            desiredPosition = AVCaptureDevicePositionBack;
            _isUsingFrontFacingCamera = NO;
        }else{
            desiredPosition = AVCaptureDevicePositionFront;
            _isUsingFrontFacingCamera = YES;
        }
        
        for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
            if ([d position] == desiredPosition) {
                [self.previewLayer.session beginConfiguration];
                AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
                for (AVCaptureInput *oldInput in self.previewLayer.session.inputs) {
                    [[self.previewLayer session] removeInput:oldInput];
                }
                [self.previewLayer.session addInput:input];
                [self.previewLayer.session commitConfiguration];
                break;
            }
        }
    }
}

- (void)saveImageFromCamera {
    
    if (!self.saveImage) {
        return;
    }
    //保存相片
    
//    PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
//    //        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
//    if (author == PHAuthorizationStatusRestricted || author == PHAuthorizationStatusDenied){
//        //无权限
//        return ;
//    }
//    __block NSString *createdAssetID =nil;//唯一标识，可以用于图片资源获取
//    NSError *error;
//    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
//        createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageWithData:_jpegData]].placeholderForCreatedAsset.localIdentifier;
//    } error:&error];
}

//缩放手势 用于调整焦距
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer{
    
    BOOL allTouchesAreOnThePreviewLayer = YES;
    NSUInteger numTouches = [recognizer numberOfTouches], i;
    for ( i = 0; i < numTouches; ++i ) {
        CGPoint location = [recognizer locationOfTouch:i inView:self.backView];
        CGPoint convertedLocation = [self.previewLayer convertPoint:location fromLayer:self.previewLayer.superlayer];
        if ( ! [self.previewLayer containsPoint:convertedLocation] ) {
            allTouchesAreOnThePreviewLayer = NO;
            break;
        }
    }
    
    if ( allTouchesAreOnThePreviewLayer ) {
        
        
        self.effectiveScale = self.beginGestureScale * recognizer.scale;
        if (self.effectiveScale < 1.0){
            self.effectiveScale = 1.0;
        }
        
        NSLog(@"%f-------------->%f------------recognizerScale%f",self.effectiveScale,self.beginGestureScale,recognizer.scale);
        
        CGFloat maxScaleAndCropFactor = [[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor];
        
        NSLog(@"%f",maxScaleAndCropFactor);
        if (self.effectiveScale > maxScaleAndCropFactor)
            self.effectiveScale = maxScaleAndCropFactor;
        
        [CATransaction begin];
        [CATransaction setAnimationDuration:.025];
        [self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
        [CATransaction commit];
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
